import os
import requests
import json
from dotenv import load_dotenv

load_dotenv()  # 加载.env中的API密钥


api_key = "Bearer ElsGbbxmZORSUUvMderu:YvOJvoxypMNikdmTfDwY"
url = "https://spark-api-open.xf-yun.com/v2/chat/completions"

# 请求模型，并将结果输出
def get_answer(message):
    headers = {
        'Authorization': api_key,
        'content-type': "application/json"
    }
    body = {
        "model": "x1",
        "user": "user_id",
        "messages": [
        {
            "role": "system",
            "content": "请根据以下信息为用户生成3-5个合适的名字，严格按照 JSON 格式返回,并尽可能快的给出回复，字段说明：每个元素是 {'name': '名字', \"meaning\": \"寓意\", \"reason\": \"命理/文化分析\"}\n示例返回（严格参考）：\n{{\n  \n  \"names\": [\n    {{\"name\": \"若曦\", \"meaning\": \"若朝阳，曦晨光\", \"reason\": \"命理喜火，‘曦’补火；文化取自‘晨起理荒秽’\"}},\n    {{\"name\": \"怀瑾\", \"meaning\": \"怀美玉，喻德厚\", \"reason\": \"命理缺土，‘瑾’属土；出自《怀沙》‘怀瑾握瑜’\"}}\n  ]\n}}"
        },
        {
            "role": "user",
            "content": message
        }
        ],
        "stream": True,
        "tools": [
            {
                "type": "web_search",
                "web_search": {
                    "enable": True,
                    "search_mode": "deep"
                }
            }
        ]
    }
    
    response = requests.post(url=url,json= body,headers= headers,stream= True)
    # print(response)
    full_response = ""
    for chunks in response.iter_lines():
        # 打印返回的每帧内容
        # print(chunks)
        if (chunks and '[DONE]' not in str(chunks)):
            data_org = chunks[6:]

            chunk = json.loads(data_org)
            text = chunk['choices'][0]['delta']
            # 判断思维链状态并输出
            if ('reasoning_content' in text and '' != text['reasoning_content']):
                reasoning_content = text["reasoning_content"]
                #print(reasoning_content, end="")
            # 判断最终结果状态并输出
            if ('content' in text and '' != text['content']):
                content = text["content"]
                #print(content, end="")
                full_response += content
    response_data = full_response     
    # 转换为JSON字符串并返回
    return json.dumps(response_data, ensure_ascii=False, indent=2)


# 提示词模板
PROMPT_TEMPLATE = PROMPT_TEMPLATE = """
信息：
姓氏：{surname}
性别：{gender}
出生日期：{birthDate}
寓意期望：{expectation}

"""
def getText(text,role, content):
    jsoncon = {}
    jsoncon["role"] = role
    jsoncon["content"] = content
    text.append(jsoncon)
    return text

def generate_names(user_data):
    """生成名字主函数，根据配置调用本地或在线模型"""
    # 填充提示词模板
    prompt = PROMPT_TEMPLATE.format(
        surname=user_data.get('surname', ''),
        gender=user_data.get('gender', '男'),
        birthDate=user_data.get('birthDate', ''),
        expectation=user_data.get('expectation', ''),
    )
    print(prompt)
    content = get_answer(prompt)
    #print(content)
    name_list = []
    #names = "```json\n{\n  \"names\": [\n    {\"name\": \"王毅轩\", \"meaning\": \"毅志如山，气宇轩昂\", \"reason\": \"‘毅’含坚毅刚强之意，契合命主五行土旺（2005乙酉年），土厚载物；‘轩’属火，调和寒露之冷，文化出自《周易》‘刚健中正’\"},\n    {\"name\": \"王铮岩\", \"meaning\": \"金石为铮，磐石作岩\", \"reason\": \"‘铮’属金，补命主冬月水旺缺金；‘岩’属土，应乙酉年命理根基，取意《诗经》‘他山之石’喻坚韧\"},\n    {\"name\": \"王曜松\", \"meaning\": \"星曜长空，青松傲霜\", \"reason\": \"‘曜’属火暖冬寒，‘松’属木疏土壅，五行流转有情；文化意象取自《礼记》‘岁寒松柏’喻顽强\"}\n  ]\n}\n```"
    names=json.loads(content)
    try:
        names_data = json.loads(names.strip('```json\n').strip('\n```'))
        print(names_data)
        names_list = names_data.get('names', [])
    except json.JSONDecodeError:
        names_list = []
        
    if len(names_list) < 3:
        names_list += [{"name": "示例名", "meaning": "寓意解释", "reason": "补充示例"}] * (3 - len(names))
    result = names_list
    print(result)
    return result
